package channelService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-channel-common/channelLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/ChanSyncObj"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Hex"
	"net"
)

type executeService struct {
}

func (e *executeService) execute(ctx net.Conn, requestVO *commRedisRpc.ChannelRequestVO) (*commRedisRpc.ChannelRespondVO, error) {
	if requestVO.Send == nil || requestVO.Send == "" {
		return nil, errors.New("发送数据不能为空！")
	}
	if requestVO.Timeout == 0 {
		return nil, errors.New("超时参数不能为空！")
	}

	// 格式转换
	send := Hex.DecodeString(requestVO.Send)

	// 发送数据
	_, err := ctx.Write(send)
	if err != nil {
		return nil, err
	}

	// 打印日志
	channelLogger.PrintChannelDebugLogger(requestVO.Name, "发送", requestVO.Send.(string))

	// 等待数据返回
	data := ChanSyncObj.Wait(requestVO.Name, int64(requestVO.Timeout))
	if data == nil {
		return nil, errors.New("接收socket数据返回失败:设备响应超时！")
	}
	buffer := data.([]byte)
	recv := Hex.EncodeToString(buffer)

	// 打印日志
	channelLogger.PrintChannelDebugLogger(requestVO.Name, "接收", recv)

	respondVO := commRedisRpc.Type.ChannelRespondVO.Ok(requestVO)
	respondVO.Recv = recv
	return respondVO, nil
}
